package jude.java.money.batch.task;

import static jude.java.money.batch.Definition.FAILURE;
import static jude.java.money.batch.Definition.IGNORE;
import static jude.java.money.batch.Definition.SUCCESS;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Keys;
import jude.java.money.batch.Parameter;
import jude.java.money.batch.memory.Sites;
import jude.java.money.batch.task.expand.UpdateCodeTask;
import jude.java.util.FileUtils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;

/**
 * 批量增加或修改文件
 * */
public class BatchUpdate extends BatchTask<String[][]> implements UpdateCodeTask {
	
	public BatchUpdate(Parameter<String[][]> p) {
		super(p);
	}
	
	private String getCode(boolean mustExists, boolean tpl) {
		return "$path=get_path($_POST['path']);\r\n" +
				"$size=$_POST['size'];\r\n"+
		(mustExists ? "if(!file_exists($path))die('"+IGNORE+"not-exists');\r\n" : "")+
		"if(!file_exists(dirname($path)))\r\n" +
		"	mkdir(dirname($path),0777,true);\r\n" +
		"if(file_exists($path) && !is_writable($path) || !file_exists($path) && !is_writable(dirname($path)))\r\n" +
		"	die('not-writable');\r\n"+
		"$file = fopen($path,\"w+\");\r\n"+
		"$content=get_magic_quotes_gpc()==1?stripslashes($_POST['content']):$_POST['content'];\r\n"+
		"$count=fwrite($file,$content);\r\n"+
		"fclose($file);\r\n" +
		"$_size=filesize($path);\r\n"+
		"if ($count==$size&&$count===$_size)\r\n"+
		"	echo '"+SUCCESS+"';\r\n"+
		"else\r\n"+
		"	echo \""+FAILURE+" $count/$size/$_size\";\r\n"+
		"die();" +
		"function get_path($path){\r\n"+
		(tpl?"$tpl=get_template_dir();" +
		"	if(!$tpl)die('cant-get-tpl-name');" +
		"	$path = str_replace('"+Keys.TEMPLATE+"', $tpl, $path);\r\n":"")+
		"	return $path;\r\n"+
		"}\r\n"+
		"\r\n"+
		(tpl?"function get_template_dir(){\r\n"+
		"	$sql = \"select template_dir from \" . DB_PREFIX . \"template_select where template_language=0\";\r\n"+
		"	$con = mysql_connect(DB_SERVER,DB_SERVER_USERNAME,base64_decode(DB_SERVER_PASSWORD));\r\n"+
		"	mysql_select_db(DB_DATABASE,$con);\r\n"+
		"	$rst = mysql_query($sql,$con);\r\n"+
		"	$row = mysql_fetch_array($rst);\r\n"+
		"	return $row['template_dir'];\r\n"+
		"}":"");
	}
	
	@Override
	protected String getLabel() {
		return "MOD";
	}
	
	protected void execute(String site, String url, int group, int index) throws IOException {
		HttpClient client = getHttpClient();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair key = new NameValuePair("key", P.KEY);
		String[][] updates = P.PARAMS;
		for (int i = 0; i < updates.length; i++) {
//			print("\r\n").print(i+1).print("\t");
			params.clear();
			params.add(key);
			String local = updates[i][0];
			if (P.TYPE == Definition.TYPE_ZENCART) {
				if (local.contains(Keys.TEMPLATE)) {
					String template = Sites.getTemplateDir(site);
					if (template == null) {
						L.result(i, "template_dir not set");
						continue;
					}
					local = StringUtils.replace(local, Keys.TEMPLATE, template);
				}
			}
			String path = updates[i].length == 1 ? null : updates[i][1];
			boolean tpl = false;
			if (StringUtils.isEmpty(path))
				path = local;
			else
				tpl = path.contains(Keys.TEMPLATE);
			path = FileUtils.normalizePath(path);
			if (path.contains(Keys.BACKEDN)) {
				String backend = Sites.getBackend(site);
				if (StringUtils.isEmpty(backend)) {
					backend = "money";
				}
				path = StringUtils.replace(path, Keys.BACKEDN, backend);
			}
			params.add(new NameValuePair("path", path));
			String code = getCode(P.FLAG == 1, tpl);
			params.add(new NameValuePair("value", code));
			String localPath = getLocalPath(local);
			String size = String.valueOf(new File(localPath).length());
			params.add(new NameValuePair("size", size));
			String content = readFile(localPath);
			if (content == null) {
				L.result(i, "local-not-exists");
				continue;
			}
			params.add(new NameValuePair("content", content));
			PostMethod post = getPostMethod(url, params);
			shieldPost(i, site, client, post);
		}
	}
	
	@Override
	protected void createPatch() {
		String[][] params = P.PARAMS;
		for (int i = 0; i < params.length; i++) {
			createPatch(params[i][0]);
		}
	}
}
